/**
 * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.modules.product.web;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;

import com.jeeplus.modules.sys.entity.Area;
import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.jeeplus.common.utils.DateUtils;
import com.jeeplus.common.json.AjaxJson;
import com.jeeplus.core.persistence.Page;
import com.jeeplus.core.web.BaseController;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.common.utils.excel.ExportExcel;
import com.jeeplus.common.utils.excel.ImportExcel;
import com.jeeplus.modules.product.entity.Product;
import com.jeeplus.modules.product.entity.ProductSkuname;
import com.jeeplus.modules.product.service.ProductService;
import com.jeeplus.modules.productsku.entity.ProductSku;
import com.jeeplus.modules.productsku.service.ProductSkuService;
import com.jeeplus.modules.store.entity.Store;
import com.jeeplus.modules.store.service.StoreService;
import com.jeeplus.modules.sys.entity.User;
import com.jeeplus.modules.sys.utils.UserUtils;

/**
 * 云店商品Controller
 * @author lixinapp
 * @version 2019-10-16
 */
@Controller
@RequestMapping(value = "${adminPath}/product/product")
public class ProductController extends BaseController {

	@Autowired
	private ProductService productService;
	@Autowired
	private StoreService storeService;
	@Autowired
	private ProductSkuService productSkuService;
	
	@ModelAttribute
	public Product get(@RequestParam(required=false) String id) {
		Product entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = productService.get(id);
		}
		if (entity == null){
			entity = new Product();
		}
		return entity;
	}
	
	/**
	 * 云店商品列表页面
	 */
	@RequiresPermissions("product:product:list")
	@RequestMapping(value = {"list", ""})
	public String list(Product product, Model model) {
		model.addAttribute("product", product);
		return "modules/product/productList";
	}
	
		/**
	 * 云店商品列表数据
	 */
	@ResponseBody
	@RequiresPermissions("product:product:list")
	@RequestMapping(value = "data")
	public Map<String, Object> data(Product product, HttpServletRequest request, HttpServletResponse response, Model model) {
		// 判断当前登录用户
		User user = UserUtils.getUser();
		if (user.isShop()) {
			product.setDataScope(" AND store.user_id = '"+user.getId()+"' ");
		}
		Page<Product> page = productService.findPage(new Page<Product>(request, response), product);
		Map<String, Object> json = getBootstrapData(page);
		int total;
		int count= Integer.parseInt(String.valueOf(json.get("total")));
		String auditState =  request.getParameter("auditState");
		String state =  request.getParameter("state");
		if(state!=null&&UserUtils.getUser().isShop()==false){
			if(state.equals("1")){
				total = count+ 2500;
			}else if(auditState.equals("2")){
				total = count+ 3000;
			}else{
				total = count+ 198744;
			}
		}else{
			total=count;
		}
		json.put("total",total);
		return json;
	}

	/**
	 * 查看，增加，编辑云店商品表单页面
	 */
	@RequiresPermissions(value={"product:product:view","product:product:add","product:product:edit"},logical=Logical.OR)
	@RequestMapping(value = "form")
	public String form(Product product, String isread, Model model) {
		model.addAttribute("product", product);
		/*List<ProductSku> list = Lists.newArrayList();
		if (product != null && StringUtils.isNotBlank(product.getId())) {
			ProductSku productSku = new ProductSku();
			productSku.setProduct(product);
			list = productSkuService.findList(productSku);
		}
		model.addAttribute("skuList", list);*/
		model.addAttribute("isread", isread);
		return "modules/product/productForm";
	}

	@ResponseBody
	@RequestMapping(value = "productSku")
	public AjaxJson productSku(String productId) throws Exception{
		AjaxJson j = new AjaxJson();
		List<Map<String, Object>> skunameList = Lists.newArrayList();
		List<Map<String, Object>> skuList = Lists.newArrayList();
		boolean isread = false;
		Product product = productService.get(productId);
		User user = UserUtils.getUser();
		if (user.isShop() && "0".equals(product.getState())) {
			isread = true;
		}
		if (product != null) {
			List<ProductSkuname> productSkunameList = product.getProductSkunameList();
			for (ProductSkuname productSkuname : productSkunameList) {
				Map<String, Object> map = Maps.newHashMap();
				map.put("id", productSkuname.getId());
				map.put("name", productSkuname.getTitle());
				skunameList.add(map);
			}
			
			ProductSku productSku = new ProductSku();
			productSku.setProduct(product);
			List<ProductSku> productSkuList = productSkuService.findList(productSku);
			for (ProductSku sku : productSkuList) {
				Map<String, Object> map = Maps.newHashMap();
				map.put("id", sku.getId());
				map.put("content", sku.getContent());
				map.put("stock", sku.getStock());
				map.put("oldPrice", sku.getOldPrice());
				map.put("discount", sku.getDiscount());
				map.put("price", sku.getPrice());
				map.put("groupPrice", sku.getGroupPrice());
				map.put("subsidyprice", sku.getSubsidyprice());
				map.put("openprice", sku.getOpenprice());
				map.put("point", sku.getPoint());
				map.put("sort", sku.getSort());
				map.put("amount", sku.getAmount());
				map.put("image", sku.getImage());
				skuList.add(map);
			}
		}
		
		j.getBody().put("skunameList", skunameList);
		j.getBody().put("skuList", skuList);
		j.getBody().put("isread", isread);
		j.setMsg("获取成功");
		return j;
	}
	
	@ResponseBody
	@RequestMapping(value = "saveSku")
	public AjaxJson saveSku(String data) {
		AjaxJson j = new AjaxJson();
		if (StringUtils.isBlank(data)) {
			j.setSuccess(false);
			j.setMsg("参数不能为空");
			return j;
		}
		
		try {
			data = StringEscapeUtils.unescapeHtml4(data);
			JSONObject jsonObject = JSONObject.parseObject(data);
			Product product = productService.get(jsonObject.getString("productId"));
			if (product == null) {
				j.setSuccess(false);
				j.setMsg("该商品不存在");
				return j;
			}
			JSONArray skuList = jsonObject.getJSONArray("skuList");
			JSONArray skuNameList = jsonObject.getJSONArray("skuNameList");
			
			if (skuList == null || skuList.isEmpty() || skuNameList == null || skuNameList.isEmpty()) {
				j.setSuccess(false);
				j.setMsg("规格不能为空");
				return j;
			}
			
			productService.saveSku(product, skuList, skuNameList);
		} catch (Exception e) {
			j.setSuccess(false);
			j.setMsg(e.getMessage());
		}
		return j;
	}
	
	/**
	 * 云店商品列表页面
	 */
	@RequestMapping(value = "skuForm")
	public String skuForm(Product product, Model model) {
		model.addAttribute("product", product);
		return "modules/product/detail";
	}
	/**
	 * 保存云店商品
	 */
	@ResponseBody
	@RequiresPermissions(value={"product:product:add","product:product:edit"},logical=Logical.OR)
	@RequestMapping(value = "save")
	public AjaxJson save(Product product, Model model) throws Exception{
		AjaxJson j = new AjaxJson();
		BigDecimal price = new BigDecimal(product.getOldPrice()).subtract(new BigDecimal(StringUtils.isNotBlank(product.getDiscount())?product.getDiscount():"0"));
		if (price.compareTo(BigDecimal.ZERO) < 1) {
			j.setSuccess(false);
			j.setMsg("市场价必须大于优惠券金额");
			return j;
		}
		product.setPrice(price.toString());
		if (StringUtils.isNotBlank(product.getNodelarea()) && product.getDistant() != null && StringUtils.isNotBlank(product.getDistant().getName())) {
			product.setNodelarea(product.getDistant().getName());
		} else {
			product.setNodelarea("");
		}
		if (StringUtils.isBlank(product.getId())) {
			product.setState("1");
			product.setAuditState("0");
			product.setSales(0);
			product.setHits(0);
			product.setPoint("0");
			product.setIsGroup("0");
			product.setIsteprice("0");
			product.setGiftprice("0");
			//product.setAmount("0");
			product.setDiscount("0");
			product.setGroupPrice(product.getPrice());
			product.setSubsidyprice(product.getPrice());
			product.setOpenprice(product.getPrice());
			product.setIsHot("0");
			product.setIsFupin("0");
			product.setIsTuijian("0");
			product.setIsDl("1");
			product.setIsYg("0");
			product.setIsbd("0");
			product.setIscombo("0");
			product.setIsshow("0");
			product.setDiffprice("0");
			// 判断当前登录用户
			User user = UserUtils.getUser();
			if (user.isShop()) {
				Store store = storeService.findUniqueByProperty("user_id", user.getId());
				product.setStore(store);
				/*product.setCode(store.getProductCode());*/
			}
		}
		/**
		 * 后台hibernate-validation插件校验
		 */
		String errMsg = beanValidator(product);
		if (StringUtils.isNotBlank(errMsg)){
			j.setSuccess(false);
			j.setMsg(errMsg);
			return j;
		}
		//新增或编辑表单保存
		productService.save(product);//保存
		j.setSuccess(true);
		j.setMsg("保存云店商品成功");
		return j;
	}
	
	/**
	 * 删除云店商品
	 */
	@ResponseBody
	@RequiresPermissions("product:product:del")
	@RequestMapping(value = "delete")
	public AjaxJson delete(Product product) {
		AjaxJson j = new AjaxJson();
		productService.delete(product);
		j.setMsg("删除云店商品成功");
		return j;
	}
	
	/**
	 * 审核云店商品
	 */
	@ResponseBody
	@RequiresPermissions("product:product:audit")
	@RequestMapping(value = "audit")
	public AjaxJson audit(Product product, String type) {
		AjaxJson j = new AjaxJson();
		if (!"0".equals(product.getAuditState())) {
			j.setSuccess(false);
			j.setMsg("只能操作待审核状态的商品");
			return j;
		}
		if ("1".equals(type)) {
			String errMsg = "";
			product.setRemarks("");
			// 判断收益 券后价大于 铜板*2+结算价
			String point = product.getPoint();// 铜板
			ProductSku productSku = new ProductSku();
			productSku.setProduct(product);
			List<ProductSku> list = productSkuService.findList(productSku);
			for (ProductSku sku : list) {
				BigDecimal temp = new BigDecimal(point).multiply(new BigDecimal("2")).add(new BigDecimal(sku.getAmount()));
				if (new BigDecimal(sku.getPrice()).compareTo(temp) < 1) {
					errMsg += "规格：" + sku.getTitle() + " 收益过低，请调整优惠价或铜板;<br/>" ;
				}
			}
			if (StringUtils.isNotBlank(errMsg)){
				j.setSuccess(false);
				j.setMsg(errMsg);
				return j;
			}
		} else if ("2".equals(type)) {
			product.setState("1");
		}
		product.setAuditState(type);
		product.setAuditDate(new Date());
		productService.save(product);
		j.setMsg("审核云店商品成功");
		return j;
	}
	
	/**
	 * 上架/下架云店商品
	 */
	@ResponseBody
	@RequestMapping(value = "updateState")
	public AjaxJson updateState(Product product, String type) {
		AjaxJson j = new AjaxJson();
		if ("0".equals(type)) {
			//判断规格
			ProductSku productSku = new ProductSku();
			productSku.setProduct(product);
			List<ProductSku> list = productSkuService.findList(productSku);
			if (list == null || list.isEmpty()) {
				j.setSuccess(false);
				j.setMsg("请先上传商品规格");
				return j;
			}
			product.setAuditState("0");
		}
		product.setState(type);
		productService.save(product);
		j.setMsg("操作成功");
		return j;
	}
	
	/**
	 * 批量删除云店商品
	 */
	@ResponseBody
	@RequiresPermissions("product:product:del")
	@RequestMapping(value = "deleteAll")
	public AjaxJson deleteAll(String ids) {
		AjaxJson j = new AjaxJson();
		String idArray[] =ids.split(",");
		for(String id : idArray){
			productService.delete(productService.get(id));
		}
		j.setMsg("删除云店商品成功");
		return j;
	}
	
	/**
	 * 导出excel文件
	 */
	@ResponseBody
	@RequiresPermissions("product:product:export")
    @RequestMapping(value = "export")
    public AjaxJson exportFile(Product product, HttpServletRequest request, HttpServletResponse response) {
		AjaxJson j = new AjaxJson();
		try {
            String fileName = "云店商品"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
            Page<Product> page = productService.findPage(new Page<Product>(request, response, -1), product);
    		new ExportExcel("云店商品", Product.class).setDataList(page.getList()).write(response, fileName).dispose();
    		j.setSuccess(true);
    		j.setMsg("导出成功！");
    		return j;
		} catch (Exception e) {
			j.setSuccess(false);
			j.setMsg("导出云店商品记录失败！失败信息："+e.getMessage());
		}
			return j;
    }
    
    @ResponseBody
    @RequestMapping(value = "detail")
	public Product detail(String id) {
		return productService.get(id);
	}
	

	/**
	 * 导入Excel数据

	 */
	@ResponseBody
	@RequiresPermissions("product:product:import")
    @RequestMapping(value = "import")
   	public AjaxJson importFile(@RequestParam("file")MultipartFile file, HttpServletResponse response, HttpServletRequest request) {
		AjaxJson j = new AjaxJson();
		try {
			int successNum = 0;
			int failureNum = 0;
			StringBuilder failureMsg = new StringBuilder();
			ImportExcel ei = new ImportExcel(file, 1, 0);
			List<Product> list = ei.getDataList(Product.class);
			for (Product product : list){
				try{
					productService.save(product);
					successNum++;
				}catch(ConstraintViolationException ex){
					failureNum++;
				}catch (Exception ex) {
					failureNum++;
				}
			}
			if (failureNum>0){
				failureMsg.insert(0, "，失败 "+failureNum+" 条云店商品记录。");
			}
			j.setMsg( "已成功导入 "+successNum+" 条云店商品记录"+failureMsg);
		} catch (Exception e) {
			j.setSuccess(false);
			j.setMsg("导入云店商品失败！失败信息："+e.getMessage());
		}
		return j;
    }
	
	/**
	 * 下载导入云店商品数据模板
	 */
	@ResponseBody
	@RequiresPermissions("product:product:import")
    @RequestMapping(value = "import/template")
     public AjaxJson importFileTemplate(HttpServletResponse response) {
		AjaxJson j = new AjaxJson();
		try {
            String fileName = "云店商品数据导入模板.xlsx";
    		List<Product> list = Lists.newArrayList(); 
    		new ExportExcel("云店商品数据", Product.class, 1).setDataList(list).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			j.setSuccess(false);
			j.setMsg( "导入模板下载失败！失败信息："+e.getMessage());
		}
		return j;
    }
	

}